<script setup lang="ts">
  import {ref, onBeforeMount, onBeforeUnmount, defineEmits} from 'vue'
  import {Notebook} from "@icon-park/vue-next"
  import {Edit} from "@icon-park/vue-next";
  import {DeleteOne} from "@icon-park/vue-next";
  import {FileAdditionOne} from "@icon-park/vue-next";
  import {FolderPlus} from "@icon-park/vue-next";
  import {Return} from "@icon-park/vue-next"
  import {Notes} from "@icon-park/vue-next"
  import {More} from "@icon-park/vue-next"
  import {Plus} from "@icon-park/vue-next"
  import {Left} from "@icon-park/vue-next"

  import {ElMessageBox, ElMessage} from "element-plus";
  import {getAllNotesAPI, addNoteAPI, delNoteByIdAPI, updateNoteAPI, updateNoteNameAPI} from "@/api/note"
  import {getNotebooksAPI, addNotebookAPI, updateNotebookAPI, delNotebookByIdAPI} from "@/api/notebook"
  import {currentUser, currentNote, setCurrentNote, currentNotebooks, updateNotebooks} from "@/global"

  const emits = defineEmits(['collapse'])

  const currentMode = ref('notebook'); // 显示笔记本或者笔记本中的文档
  const selectedNotebook = ref({
    id: -1,
    name: ""
  });  // 当前正在浏览的笔记本，在笔记本中新增笔记时需要使用

  const setSelectedNotebook = (notebookId, name) => {
    selectedNotebook.value.id = notebookId;
    selectedNotebook.value.name = name;
  }

  const changeMode = (type: string) =>{
    currentMode.value = type;
  }

  const displayNotes = async (notebookId) => {
    await getNotes(notebookId);
    changeMode("note");
  }

  const renameNotebook = (notebook) => {
    ElMessageBox.prompt('新的名称', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      inputPattern: /.+/,
      inputErrorMessage: '请输入新的名称！',
    })
        .then(async ({ value }) => {
          notebook.name = value;
          await updateNotebookAPI(notebook)
              .catch((err) => {
                ElMessage.error(err.response.data)
              })
          await updateNotebooks();
        })
  }

  const delNotebook = async (notebook) => {
    await delNotebookByIdAPI(notebook.id);
    await updateNotebooks();
    if (currentNote.value.notebookId === notebook.id) {
      setCurrentNote(-1, "", -1);
    }
  }

  const addNotebook = () => {
    ElMessageBox.prompt('新笔记本的名称', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      inputPattern: /.+/,
      inputErrorMessage: '请输入名称！',
    })
        .then(async ({ value }) => {
          const data = {"name": value, "userid": currentUser.value.id};
          await addNotebookAPI(data)
              .then((response) => {
                updateNotebooks();
                ElMessage.success("创建成功");
              })
              .catch((err) => {
                ElMessage.error(err.response.data.message)
              })
        })
  }

  let allNotes = ref([]);

  const getNotes = async (notebookId) => {
    await getAllNotesAPI(notebookId)
        .then((response) => {
          allNotes = ref(response);
        })
  }

  const renameNote = (note) => {
    ElMessageBox.prompt('新的名称', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      inputPattern: /.+/,
      inputErrorMessage: '请输入新的名称！',
    })
        .then(async ({ value }) => {
          const oldName = note.name;
          note.name = value;
          await updateNoteNameAPI(note)
              .catch((err) => {
                note.name = oldName;
                ElMessage.error(err.response.data);
              })
        })
  }

  const delNote = async (note) => {
    await delNoteByIdAPI(note.id);
    if (note.id === currentNote.value.noteId) {
      setCurrentNote(-1, "", -1);
    }
    const listId = allNotes.value.indexOf(note);
    allNotes.value.splice(listId, 1);
  }

  const addNote = () => {
    ElMessageBox.prompt('新笔记的名称', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      inputPattern: /.+/,
      inputErrorMessage: '请输入名称！',
    })
      .then(async ({ value }) => {
        await addNoteAPI({
          "userid": currentUser.value.id,
          "content": "",
          "name": value,
          "notebookid": selectedNotebook.value.id
        })
            .then((response) => {
              allNotes.value.push(response);
              ElMessage.success("创建成功")
              setCurrentNote(response.id, response.name, selectedNotebook.value.id)
            })
            .catch((err) => {
              ElMessage.error(err.response.data.message)
            })
      })
  }
</script>

<template>
  <div id="body">
    <left id="collapse-btn" theme="outline" size="24" fill="#000000" @click="emits('collapse')"/>
    <!-- 显示笔记本的操作栏 -->
    <div v-if="currentMode==='notebook'" class="operationBar">
      <el-tooltip effect="dark" content="新增笔记本" placement="bottom">
        <folder-plus class="icon" theme="outline" size="20" @click="addNotebook"/>
      </el-tooltip>
    </div>
    <!-- 显示笔记的操作栏 -->
    <div v-else class="operationBar" style="justify-content: space-between">
      <div style="margin-left: 0.15rem">
        <el-tooltip effect="dark" content="返回笔记本" placement="bottom">
          <return class="icon" theme="outline" size="20" fill="#333" style="align-self: start" @click="changeMode('notebook')"/>
        </el-tooltip>
      </div>
      <div class="operationBar__text">{{selectedNotebook.name}}</div>
      <el-tooltip effect="dark" content="新增笔记" placement="bottom">
        <file-addition-one class="icon" theme="outline" size="20" @click="addNote"/>
      </el-tooltip>
    </div>

    <div id="content">
      <!-- 显示笔记本 -->
      <div v-if="currentMode==='notebook' && currentNotebooks.length === 0">
        <div class="addBtn" @click="addNotebook">
          <plus theme="outline" size="24" fill="#c8c8c8"/>
          <div>新建笔记本</div>
        </div>
      </div>
      <div v-else-if="currentMode==='notebook' && currentNotebooks.length > 0"  v-for="notebook in currentNotebooks" class="display-item">
        <div class="display-item-icon-and-text"  @click="setSelectedNotebook(notebook.id, notebook.name); displayNotes(notebook.id);">
          <notebook class="icon" theme="multi-color" size="16" :fill="['#333' ,'#40afa0' ,'#FFF']"/>
          <div class="display-item-text">{{notebook.name}}</div>
        </div>
        <!-- 弹出框进行重命名和删除操作 -->
        <el-popover placement="bottom-start" :width="100" trigger="click" hide-after="0">
          <template #default>
            <div class="popover-item" @click="renameNotebook(notebook)">
              <edit class="icon" theme="outline" size="20" fill="#000000"/>
              <div style="margin-left: 0.5rem">重命名</div>
            </div>
            <el-popconfirm width="100" confirm-button-text="确定" cancel-button-text="取消" title="确认删除？"  @confirm="delNotebook(notebook)">
              <template #reference>
                <div class="popover-item">
                  <delete-one class="icon" theme="outline" size="20" fill="#000000"/>
                  <div style="margin-left: 0.5rem">删除</div>
                </div>
              </template>
            </el-popconfirm>
          </template>
          <template #reference>
            <more theme="outline" size="16" fill="#333" @click=""/>
          </template>
        </el-popover>
      </div>

      <!-- 显示笔记本中的笔记 -->
      <div v-else-if="currentMode==='note' && allNotes.length === 0">
        <div class="addBtn" @click="addNote">
          <plus theme="outline" size="24" fill="#c8c8c8"/>
          <div>新建笔记</div>
        </div>
      </div>
      <div v-else-if="currentMode==='note' && allNotes.length > 0" class="display-item" v-for="note in allNotes">
        <div class="display-item-icon-and-text" @click="setCurrentNote(note.id, note.name, selectedNotebook.id)">
         <notes class="icon" theme="multi-color" size="16" :fill="['#333' ,'#40afa0' ,'#FFF']"/>
         <div class="display-item-text">{{note.name}}</div>
        </div>
        <!-- 弹出框进行重命名和删除操作 -->
        <el-popover placement="bottom-start" :width="100" trigger="click" hide-after="0">
          <template #default>
            <div class="popover-item" @click="renameNote(note)">
              <edit class="icon" theme="outline" size="20" fill="#000000"/>
              <div style="margin-left: 0.5rem">重命名</div>
            </div>
            <el-popconfirm width="100" confirm-button-text="确定" cancel-button-text="取消" title="确认删除？" @confirm="delNote(note)">
              <template #reference>
                <div class="popover-item">
                  <delete-one class="icon" theme="outline" size="20" fill="#000000"/>
                  <div style="margin-left: 0.5rem">删除</div>
                </div>
              </template>
            </el-popconfirm>
          </template>
          <template #reference>
            <more theme="outline" size="16" fill="#333"/>
          </template>
        </el-popover>
      </div>
    </div>

  </div>
</template>

<style scoped>
  #body {
    position: relative;
    background-color: transparent;
    display: flex;
    flex-direction: column;
  }

  #collapse-btn {
    position: absolute;
    top: 50%;
    left: 100%;
    transform: translate(-100%, -50%);
    cursor: pointer;
  }

  #content {
    overflow: scroll;
    flex-grow: 0;
  }
  #content::-webkit-scrollbar {
    display: none;
  }

  .operationBar {
    display: flex;
    justify-content: flex-end;
    padding: 5px 10px 5px 0;
    border-bottom: 1px solid #e9e9e9;
    background-color: white;
  }

  .operationBar__text {
    font-size: 14px;
    font-weight: bold;
    max-width: 60%;
    text-overflow: ellipsis;
    overflow: hidden;
  }

  .addBtn {
    border: 2px dashed rgb(160, 160, 160);
    border-radius: 5px;
    margin: 10px 10% 0 10%;
    display: flex;
    flex-direction: column;
    align-items: center;
    cursor: pointer;
    color: rgb(160, 160, 160);
    padding: 5px;
  }
  .addBtn:hover {
    background-color: rgb(240,240,240, 0.5);
  }

  .display-item {
    display: flex;
    align-items: center;
    cursor: pointer;
    padding-right: 0.7rem;
  }
  .display-item:hover {
    background-color: rgb(240,240,240,0.5);
  }

  .display-item-icon-and-text {
    display: flex;
    width: 85%;
    padding: 1rem 0.7rem 1rem 1rem;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .display-item-text {
    margin-left: 5%;
    font-size: 0.8rem;
    font-weight: bold;
    max-width: 80%;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .popover-item {
    display: flex;
    align-items: center;
    cursor:pointer;
    padding: 0.5rem;
  }
  .popover-item:hover {
    background-color: rgb(240,240,240,0.5);
    border-radius: 10px;
  }
</style>